from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database.database import get_db
from crud import user_stats
from schemas.user_stats import TTSStatsRequest, ASRStatsRequest, UserStatsQuery
from typing import List, Optional
from datetime import date

router = APIRouter()

# 更新TTS统计
@router.post("/tts")
def update_tts_stats(request: TTSStatsRequest, db: Session = Depends(get_db)):
    """更新用户TTS统计"""
    return user_stats.update_tts_stats(db, request)

# 更新ASR统计
@router.post("/asr")
def update_asr_stats(request: ASRStatsRequest, db: Session = Depends(get_db)):
    """更新用户ASR统计"""
    return user_stats.update_asr_stats(db, request)

# 获取用户统计
@router.get("/user/{user_id}")
def get_user_stats(
    user_id: int,
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)"),
    db: Session = Depends(get_db)
):
    """获取用户统计信息"""
    # 转换日期字符串为date对象
    start = None
    end = None
    
    if start_date:
        try:
            start = date.fromisoformat(start_date)
        except ValueError:
            raise HTTPException(status_code=400, detail="开始日期格式错误，请使用YYYY-MM-DD格式")
    
    if end_date:
        try:
            end = date.fromisoformat(end_date)
        except ValueError:
            raise HTTPException(status_code=400, detail="结束日期格式错误，请使用YYYY-MM-DD格式")
    
    return user_stats.get_user_stats(db, user_id, start, end)

# 获取用户今日统计
@router.get("/user/{user_id}/today")
def get_user_today_stats(user_id: int, db: Session = Depends(get_db)):
    """获取用户今日统计"""
    return user_stats.get_user_today_stats(db, user_id)

# 获取用户本月统计
@router.get("/user/{user_id}/month/{year}/{month}")
def get_user_month_stats(
    user_id: int,
    year: int,
    month: int,
    db: Session = Depends(get_db)
):
    """获取用户指定月份的统计"""
    if month < 1 or month > 12:
        raise HTTPException(status_code=400, detail="月份必须在1-12之间")
    
    return user_stats.get_user_month_stats(db, user_id, year, month)

# 获取所有用户的今日统计汇总
@router.get("/today/summary")
def get_all_users_today_summary(db: Session = Depends(get_db)):
    """获取所有用户的今日统计汇总"""
    return user_stats.get_all_users_today_summary(db)

# 全局统计接口
@router.get("/global/today")
def get_global_today_stats(db: Session = Depends(get_db)):
    """获取所有用户今日统计汇总"""
    return user_stats.get_global_today_stats(db)

@router.get("/global/month/{year}/{month}")
def get_global_month_stats(year: int, month: int, db: Session = Depends(get_db)):
    """获取所有用户指定月份统计汇总"""
    return user_stats.get_global_month_stats(db, year, month)

@router.get("/global")
def get_global_all_stats(db: Session = Depends(get_db)):
    """获取所有用户历史统计汇总"""
    return user_stats.get_global_all_stats(db) 